#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <mqueue.h>

#define QUEUE_NAME  "/test_queue"
#define MAX_SIZE    4096
#define MSG_STOP    "exit"

int mq_rece_process()
{
    mqd_t mq = 0;
    int ret = 0;
    struct mq_attr attr;
    char buffer[MAX_SIZE + 1];

    /* initialize the queue attributes */
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_SIZE;
    attr.mq_curmsgs = 0;

    /* create the message queue */
    mq = mq_open(QUEUE_NAME, O_CREAT | O_RDONLY, 0644, &attr);
    if (mq < 0) {
        fprintf(stderr, "mq_open failed: %s\n", strerror(errno) );
        ret = -1;
        goto out;
    }

    do {
        ssize_t bytes_read;

        /* receive the message */
        bytes_read = mq_receive(mq, buffer, MAX_SIZE, NULL);
        if (bytes_read < 0) {
            fprintf(stderr, "mq_receive failed: %s\n", strerror(errno) );
            ret = -1;
            goto out;
        }

        buffer[bytes_read] = '\0';
        if (!strncmp(buffer, MSG_STOP, strlen(MSG_STOP))) {
            break;
        }
        else {
            printf("Received: %s\n", buffer);
        }
    } while (1);

out:
    if (mq > 0) {
        if (mq_close(mq)) {
            fprintf(stderr, "mq_close failed: %s\n", strerror(errno) );
        }
        mq_unlink(QUEUE_NAME);
    }
    return ret;
}

int main()
{
    mq_rece_process();
    return 0;
}